package com.hlingsoft.kkh.action.admin;

import cn.jpush.api.utils.StringUtils;
import com.aliyun.openservices.oss.OSSClient;
import com.aliyun.openservices.oss.model.ObjectMetadata;
import com.aliyun.openservices.oss.model.PutObjectResult;

import com.hlingsoft.kkh.entity.*;
import com.hlingsoft.kkh.entity.vo.EventsVo;
import com.hlingsoft.kkh.entity.vo.JsonVo;
import com.hlingsoft.kkh.entity.vo.PageVo;
import com.hlingsoft.kkh.util.Common;
import com.hlingsoft.kkh.util.HttpUtils;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.FileNotFoundException;
import java.io.InputStream;

import java.util.*;

/**
 * Created by selbylei on 2015/5/23.
 */
@Controller
@RequestMapping("/admin/events")
public class AdminEventsAction extends AdminBaseAction {


    /**
     * 活动列表
     *
     * @param pageNum
     * @param modelMap
     * @return
     */
    @RequestMapping(value = "/list.htm")
    public String list(
            @RequestParam(value = "p", defaultValue = "1") int pageNum,
            @RequestParam(value = "pushId", required = false) Integer pushId,
            @RequestParam(value = "interestId", required = false) Integer interestId,
            @RequestParam(value = "professionId", required = false) Integer professionId,
            @RequestParam(value = "createAddress", required = false) String createAddress,
            HttpServletRequest request,
            ModelMap modelMap) {

        PageVo<EventsVo> pageVo = new PageVo<EventsVo>(pageNum);
        pageVo.basePath = HttpUtils.getBasePath(request) + "/admin/events/list.htm";
        pageVo.setRows(10);

        List<EventsVo> eventsVoList = new ArrayList<EventsVo>();
        List<Events> eventsList = eventsDao.getEventsWithNone(pageVo.getOffset(), pageVo.getRows());
        for (Events events : eventsList) {
            EventsVo eventsVo = new EventsVo();
            eventsVo.setId(events.getId());
            eventsVo.setName(events.getName());

            //图片处理
            eventsVo.setImages(events.getImages());

            EventComments firstEventComments = eventCommentsDao.getFirstEventCommentsWithNone(events.getId());
            List<Image> imageList = imageDao.getImageByEventCommentsIdWithNone(firstEventComments.getId());

            eventsVo.setImageList(imageList);

            eventsVo.setDescription(events.getDescription());
            eventsVo.setAppUserId(events.getAppUserId());
            eventsVo.setCreateTime(events.getCreateTime());
            eventsVo.setUpdateTime(events.getUpdateTime());
            eventsVo.setCreateAddress(events.getCreateAddress());
            eventsVo.setLatitude(events.getLatitude());
            eventsVo.setLongitude(events.getLongitude());

            eventsVo.setInterestIds(events.getInterestIds());
            String interestIds = events.getInterestIds();
            String interests = "";
            List<Integer> interestIdList = Common.strToIntegerList(interestIds);
            for (Integer interestId2 : interestIdList) {
                Interest interest = interestDao.getInterestById(interestId2);
                if (interest != null) {
                    interests += interest.getName() + ",";
                }
            }
            if (interests.length() > 0) {
                interests = interests.substring(0, interests.length() - 1);
            }
            eventsVo.setInterests(interests);
            eventsVo.setPushId(events.getPushId());
            eventsVo.setPush(pushDao.getPushById(events.getPushId()).getName());

            eventsVo.setAvailable(events.getAvailable());

            eventsVoList.add(eventsVo);
        }

        pageVo.setList(eventsVoList);
        pageVo.setCount(eventsDao.getEventsWithNoneCount());
        modelMap.put("interestList", interestDao.getInterest());
        modelMap.put("professionList", professionDao.getProfession());
        modelMap.put("pushList", pushDao.getPush());
        modelMap.put("pageVo", pageVo);
        modelMap.put("p", pageNum);
        modelMap.put("pushId", pushId);
        modelMap.put("interestId", interestId);
        modelMap.put("professionId", professionId);
        modelMap.put("createAddress", createAddress);

        return "system/events/list";
    }


    /**
     * 添加
     *
     * @param request
     * @param modelMap
     * @return
     */
    @RequestMapping(value = "/add.htm")
    public String add(HttpServletRequest request, ModelMap modelMap) {
        modelMap.put("pushList", pushDao.getPush());
        modelMap.put("interestList", interestDao.getInterest());
        modelMap.put("kindId", System.currentTimeMillis());
        modelMap.put("JSESSIONID", request.getSession().getId());
        return "system/events/add";
    }


    /**
     * 编辑页面
     *
     * @param eventsId
     * @param request
     * @param modelMap
     * @return
     */
    @RequestMapping(value = "/edit.htm")
    public String detail(@RequestParam(value = "eventsId") long eventsId,
                         HttpServletRequest request, ModelMap modelMap) {
        Events events = eventsDao.getEventsByIdWithNone(eventsId);
        EventComments firstEventComments = eventCommentsDao.getFirstEventCommentsWithNone(eventsId);
        List<Image> imageList = imageDao.getImageByEventCommentsIdWithNone(firstEventComments.getId());
        AppUser appUser = userDao.getUserByIdWithNone(events.getAppUserId());
        modelMap.put("pushList", pushDao.getPush());
        modelMap.put("interestList", interestDao.getInterest());
        modelMap.put("imageList", imageList);
        modelMap.put("eventsUserName", appUser.getName());
        modelMap.put("events", eventsDao.getEventsByIdWithNone(eventsId));
        modelMap.put("kindId", System.currentTimeMillis());
        modelMap.put("JSESSIONID", request.getSession().getId());
        return "system/events/edit";
    }
//
//

    /**
     * 编辑json传递
     *
     * @param eventsId
     * @param name
     * @param files
     * @param description
     * @param pushId
     * @param modelMap
     * @return
     */
    @RequestMapping(value = "/edit.json")
    @ResponseBody
    public JsonVo<String> edit(
            @RequestParam(value = "eventsId") long eventsId,
            @RequestParam(value = "name", required = false) String name,
            @RequestParam(value = "files", required = false) MultipartFile[] files,
            @RequestParam(value = "description", required = false) String description,
            @RequestParam(value = "interestIds", required = false) String interestIds,
            @RequestParam(value = "pushId", required = false) Integer pushId,
            @RequestParam(value = "latitude", required = false) Double latitude,
            @RequestParam(value = "longitude", required = false) Double longitude,
            @RequestParam(value = "createAddress", required = false) String createAddress,
            ModelMap modelMap) {
        JsonVo<String> json = new JsonVo<String>();
        try {
            json.setResult(true);
            Events events = eventsDao.getEventsByIdWithNone(eventsId);

            if (name != null) {
                events.setName(name);
            }
            if (description != null) {
                events.setDescription(description);
            }
            if (interestIds != null) {
                events.setInterestIds(interestIds);
            }
            if (pushId != null) {
                events.setPushId(pushId);
            }

            if (createAddress != null) {
                events.setCreateAddress(createAddress);
            }
            if (latitude != null) {
                events.setLatitude(latitude);
            }
            if (longitude != null) {
                events.setLongitude(longitude);
            }
            eventsDao.updateEvents(events);
            return json;
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg("输入参数有误");
            json.setResult(false);
            return json;
        }
    }


    /**
     * 禁用
     *
     * @param eventsId
     * @param modelMap
     * @return
     */
    @RequestMapping(value = "/takeOff.json")
    @ResponseBody
    public JsonVo<String> takeOff(@RequestParam(value = "eventsId") long eventsId,
                                  ModelMap modelMap) {
        JsonVo<String> json = new JsonVo<String>();

        Events events = eventsDao.getEventsById(eventsId);

        if (events != null) {

            //删除相关帖子
            List<EventComments> eventCommentsList = eventCommentsDao.getCommentsListByEventIdWithNone(eventsId);
            for (EventComments eventComments : eventCommentsList) {
                eventComments.setAvailable(0);
                eventCommentsDao.updateEventComments(eventComments);
            }

            //删除相关图片
            List<Image> imageList = imageDao.getImageByEventsIdWithNone(eventsId);
            for (Image image : imageList) {
                image.setAvailable(0);
                imageDao.updateImage(image);
            }


            //删除相关点赞
            List<Likes> likesList = likesDao.getLikesByEventsIdWithNone(eventsId);
            for (Likes likes : likesList) {
                likes.setAvailable(0);
                likesDao.updateLikes(likes);
            }

            //删除相关消息
            List<Notification> notificationList = notificationDao.getNotificationByEventsIdWithNone(eventsId);
            for (Notification notification : notificationList) {
                notification.setAvailable(0);
                notificationDao.updateNotification(notification);
            }

            //删除举报
            List<Report> reportList = reportDao.getReportByEventsIdWithNone(eventsId);
            for (Report report : reportList) {
                report.setAvailable(0);
                report.setStatus(2);
                reportDao.updateReport(report);
            }

            //删除分享
            List<Share> shareList = shareDao.getShareByEventsId(eventsId);
            for (Share share : shareList) {
                share.setAvailable(0);
                shareDao.updateShare(share);
            }

            //删除社区
            events.setAvailable(0);
            eventsDao.updateEvents(events);
        } else {
            json.setMsg("活动已被删除");
        }
        json.setResult(true);
        return json;
    }

    /**
     * 启用
     *
     * @param eventsId
     * @param modelMap
     * @return
     */
    @RequestMapping(value = "/getOn.json")
    @ResponseBody
    public JsonVo<String> getOn(@RequestParam(value = "eventsId") long eventsId,
                                ModelMap modelMap) {
        JsonVo<String> json = new JsonVo<String>();
        Events events = eventsDao.getEventsByIdWithNone(eventsId);
        events.setAvailable(1);
        eventsDao.updateEvents(events);

        json.setResult(true);
        return json;
    }


    @RequestMapping(value = "/delete.json")
    @ResponseBody
    public JsonVo<String> delete(@RequestParam(value = "eventsId") long eventsId,
                                 ModelMap modelMap) {
        JsonVo<String> json = new JsonVo<String>();

        Events events = eventsDao.getEventsById(eventsId);

        if (events != null) {

            //删除跟帖
            List<EventComments> eventCommentsList = eventCommentsDao.getCommentsListByEventId(eventsId);
            for (EventComments eventComments : eventCommentsList) {
                eventComments.setAvailable(0);
                eventCommentsDao.updateEventComments(eventComments);
            }

            //删除评论
            List<Reply> replyList = replyDao.getReplyByEventsId(eventsId);
            for (Reply reply : replyList) {
                reply.setAvailable(0);
                replyDao.updateReply(reply);
            }

            //删除点赞
            List<Likes> likesList = likesDao.getAllLikesByEventsId(eventsId);
            for (Likes likes : likesList) {
                likes.setAvailable(0);
                likesDao.updateLikes(likes);
            }

            //删除分享
            List<Share> shareList = shareDao.getShareByEventsId(eventsId);
            for (Share share : shareList) {
                share.setAvailable(0);
                shareDao.updateShare(share);
            }

            //删除图片
            List<Image> imageList = imageDao.getImageByEventsId(eventsId);
            for (Image image : imageList) {
                image.setAvailable(0);
                imageDao.updateImage(image);
            }

            //删除收藏
            List<Collect> collectList = collectDao.getAllByEventsId(eventsId);
            for (Collect collect : collectList) {
                collect.setAvailable(0);
                collectDao.updateCollect(collect);
            }


            //删除相关消息
            List<Notification> notificationList = notificationDao.getNotificationByEventsId(eventsId);
            for (Notification notification : notificationList) {
                notification.setAvailable(0);
                notificationDao.updateNotification(notification);
            }

            //删除举报
            List<Report> reportList = reportDao.getReportByEventsId(eventsId);
            for (Report report : reportList) {
                report.setAvailable(0);
                reportDao.updateReport(report);
            }

            //删除
            events.setAvailable(0);
            eventsDao.updateEvents(events);
        } else {
            json.setMsg("活动已被删除");
        }
        json.setResult(true);
        return json;
    }


    public void putObject(String date, String filename, InputStream content,
                          Long size) throws FileNotFoundException {

        // 初始化OSSClient
        OSSClient client = new OSSClient("W6PVM427mSEWlvEz",
                "h7NoXlxcjCqyeOWeuT43LungGmGRSd");

        // 获取指定文件的输入流
        // File file = new File(filePath);
        // InputStream content = new FileInputStream(file);

        // 创建上传Object的Metadata
        ObjectMetadata meta = new ObjectMetadata();

        // 必须设置ContentLength
        meta.setContentLength(size);

        // 上传Object.
        PutObjectResult result = client.putObject("kkh", "upload/" + date
                + "/" + filename, content, meta);

        // 打印ETag
        System.out.println(result.getETag());
    }


    @RequestMapping(value = "/add.json")
    @ResponseBody
    public JsonVo<String> add(
            @RequestParam(value = "appUserId") Integer appUserId,
            @RequestParam(value = "name") String name,
            @RequestParam(value = "images") String images,
            @RequestParam(value = "description") String description,
            @RequestParam(value = "interestIds") String interestIds,
            @RequestParam(value = "latitude") Double latitude,
            @RequestParam(value = "longitude") Double longitude,
            @RequestParam(value = "pushId") Integer pushId,
            @RequestParam(value = "createAddress") String createAddress,
            ModelMap modelMap) {
        JsonVo<String> json = new JsonVo<String>();
        try {

            Date now = new Date();
            json.setResult(true);
            Events events = new Events();
            events.setName(name);
            events.setAppUserId(appUserId);
            events.setCreateAddress(createAddress);
            events.setPushId(pushId);

            events.setDescription(description);
            if (!StringUtils.isEmpty(images) && images.endsWith(",")) {
                images = images.substring(0, images.length() - 1);
            }
            events.setImages(images);
            if (interestIds != null) {
                events.setInterestIds(interestIds);
            }
            events.setCreateTime(now);
            events.setUpdateTime(now);
            events.setLatitude(latitude);
            events.setLongitude(longitude);
            eventsDao.addEvents(events);

            EventComments eventComments = new EventComments();
            eventComments.setContent(description);
            eventComments.setEventId(events.getId());
            eventComments.setImage(images);
            eventComments.setLikeCount(0);
            eventComments.setUnlikeCount(0);
            eventComments.setShareCount(0);
            eventComments.setAppUserId(appUserId);
            eventComments.setCreateTime(new Date());
            eventComments.setUpdateTime(new Date());
            eventComments.setType(1);
            eventCommentsDao.addEventComments(eventComments);

            List<String> pathList = Common.strToList(images);

            for (String path : pathList) {
                Image image = new Image();
                image.setPath(path);
                image.setAppUserId(appUserId);
                image.setEventCommentsId(eventComments.getId());
                image.setEventsId(events.getId());
                image.setTagId(0);
                image.setCreateTime(new Date());
                image.setUpdateTime(new Date());
                image.setTokeTime(now);
                image.setAvailable(1);
                imageDao.addImage(image);
            }

            return json;
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg("输入参数有误");
            json.setResult(false);
            return json;
        }
    }


    /**
     * 查找
     *
     * @param pushId
     * @param interestId
     * @param pageNum
     * @param request
     * @param modelMap
     * @return
     */
    @RequestMapping(value = "/search.htm")
    public String toSearchList(
            @RequestParam(value = "eventsId", required = false) Integer eventsId,
            @RequestParam(value = "pushId", required = false) Integer pushId,
            @RequestParam(value = "interestId", required = false) Integer interestId,
            @RequestParam(value = "professionId", required = false) Integer professionId,
            @RequestParam(value = "createAddress", required = false) String createAddress,
            @RequestParam(value = "p", defaultValue = "1") int pageNum,
            HttpServletRequest request,
            ModelMap modelMap) {

        PageVo<EventsVo> pageVo = new PageVo<EventsVo>(pageNum);
        pageVo.setRows(10);
        pageVo.basePath = HttpUtils.getBasePath(request) + "/admin/events/search.htm";

        List<Events> eventsList = new ArrayList<Events>();
        if (eventsId != null) {
            eventsList.add(eventsDao.getEventsByIdWithNone(eventsId));

        } else {
            eventsList = eventsDao.getSearch(createAddress, pushId, interestId.toString(), professionId);
        }
        List<EventsVo> eventsVoList = new ArrayList<EventsVo>();
        for (Events events : eventsList) {
            List<Integer> interestIdList = Common.strToIntegerList(events.getInterestIds());
            if (interestIdList.contains(interestId)) {
                EventsVo eventsVo = new EventsVo();
                eventsVo.setId(events.getId());
                eventsVo.setName(events.getName());

                //图片处理
                eventsVo.setImages(events.getImages());

                EventComments firstEventComments = eventCommentsDao.getFirstEventCommentsWithNone(events.getId());
                List<Image> imageList = imageDao.getImageByEventCommentsIdWithNone(firstEventComments.getId());

                eventsVo.setImageList(imageList);

                eventsVo.setDescription(events.getDescription());
                eventsVo.setAppUserId(events.getAppUserId());
                eventsVo.setCreateTime(events.getCreateTime());
                eventsVo.setUpdateTime(events.getUpdateTime());
                eventsVo.setCreateAddress(events.getCreateAddress());
                eventsVo.setLatitude(events.getLatitude());
                eventsVo.setLongitude(events.getLongitude());

                String interestIds = events.getInterestIds();
                String interests = "";
                for (Integer interestId2 : interestIdList) {
                    Interest interest = interestDao.getInterestById(interestId2);
                    if (interest != null) {
                        interests += interest.getName() + ",";
                    }
                }
                if (interests.length() > 0) {
                    interests = interests.substring(0, interests.length() - 1);
                }
                eventsVo.setInterests(interests);
                eventsVo.setPushId(events.getPushId());
                eventsVo.setPush(pushDao.getPushById(events.getPushId()).getName());

                eventsVo.setAvailable(events.getAvailable());

                eventsVoList.add(eventsVo);
            }
        }

        pageVo.setCount(eventsVoList.size());
        pageVo.setList(Common.fenYe(eventsVoList, pageVo.getOffset(), pageVo.getRows()));

        modelMap.put("pushList", pushDao.getPush());
        modelMap.put("interestList", interestDao.getInterest());
        modelMap.put("professionList", professionDao.getProfession());
        modelMap.put("pushId", pushId);
        modelMap.put("interestId", interestId);
        modelMap.put("professionId", professionId);
        modelMap.put("createAddress", createAddress);
        modelMap.put("p", pageNum);
        modelMap.put("pageVo", pageVo);
        return "system/events/list";
    }
}
